﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;

namespace AppManagement.BusManagers
{
    #region Using
    using AppManagement.Models;
    using AppManagement.Repositories;
    using AppManagement.Helpers;
    using AppManagement.Reports;
    #endregion

    /// <summary>
    ///  insert new khenthuong progress
    /// </summary>
    public partial class FrmLapPhieuKham : DevComponents.DotNetBar.Office2007Form
    {
        public EventHandler Handler { get; set; }
        private bool Updated = false;
        private EnumUpdateMode UpdateMode = EnumUpdateMode.INSERT;
        // Hidden files are used to store ids 
        private DevComponents.DotNetBar.Controls.TextBoxX txtMaBenhNhan;

        public FrmLapPhieuKham(string mabenhnhan)
        {
            InitializeComponent();
            InitHiddenFields();

            txtMaBenhNhan.Text = mabenhnhan;
            var benhnhan = BenhNhanRepository.SelectByID(txtMaBenhNhan.Text);
            txtBenhNhan.Text = benhnhan.ToString();
            txtBacSiLapPhieu.Text = GlobalVars.g_CurrentUser.ToString(); ;
        }

        private void btnThem_Click(object sender, EventArgs e)
        {
            UpdateMode = EnumUpdateMode.INSERT;
            EraseTextboxes();
            SetDefaultMode(false);
            DisableCmdButtons();
            txtNgayKham.Focus();
        }

        private void btnSua_Click(object sender, EventArgs e)
        {
            if (txtMaPhieu.Text != "")
            {
                UpdateMode = EnumUpdateMode.UPDATE;
                SetDefaultMode(false);
                DisableCmdButtons();
            }
        }

        private void btnXoa_Click(object sender, EventArgs e)
        {
            if (lstvData.SelectedItems.Count > 0)
            {
                if (MessageBox.Show("Bạn có chắc chắn xóa dữ liệu này không?", "Xóa", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    if (PhieuKhamRepository.Delete(txtMaPhieu.Text))
                    {
                        Updated = true;
                        EraseTextboxes();
                        txtMaPhieu.Text = "";
                        LoadData();
                        MessageBox.Show("Xóa dữ liệu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show("Xóa dữ liệu thất bại", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }

        private void btnGhi_Click(object sender, EventArgs e)
        {
            string errorText = "";
            var success = false;

            if (!ValidateUserInput(ref errorText))
            {
                MessageBox.Show(errorText, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (UpdateMode == EnumUpdateMode.INSERT)
            {
                if (ActionAdd())
                {
                    success = true;
                }
            }
            else if (UpdateMode == EnumUpdateMode.UPDATE)
            {
                if (ActionUpdate())
                {
                    success = true;
                }
            }
            // Inform result for nguoidung
            if (success)
            {
                LoadData();
                SetDefaultMode(true);
                Updated = true;
                MessageBox.Show("Cập nhật dữ liệu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("Cập nhật dữ liệu thất bại", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnHuy_Click(object sender, EventArgs e)
        {
            // Case 1
            if (txtMaPhieu.Text != "")
                LoadCurrentQuaTrinhInfo(txtMaPhieu.Text);
            else
                EraseTextboxes();

            SetDefaultMode(true);
            btnThem.Focus();
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void FrmNhapQuaTrinhKhenThuong_Load(object sender, EventArgs e)
        {
            LoadData();
            EraseTextboxes();
            SetDefaultMode(true);
            txtNgayKham.Text = String.Format("{0:dd/MM/yyyy}", DateTime.Now);
        }

        private void lstvData_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lstvData.SelectedItems.Count > 0)
            {
                var phieu = (PhieuKham)lstvData.SelectedItems[0].Tag;
                txtMaPhieu.Text = phieu.MaPK;
                LoadCurrentQuaTrinhInfo(phieu.MaPK);
            }
        }

        private void FrmNhapQuaTrinhKhenThuong_FormClosed(object sender, FormClosedEventArgs e)
        {
            
        }

        /// <summary>
        /// Load list of congtac progresses of specified nhanvien
        /// </summary>
        public void LoadData()
        {
            var lstItem = PhieuKhamRepository.SelectByMaBN(txtMaBenhNhan.Text);
            lstvData.Items.Clear();
            for (int i = 0; i < lstItem.Count; i++)
            {
                var objListViewItem = new ListViewItem();
                objListViewItem.Tag = lstItem[i];
                objListViewItem.Text = (i + 1).ToString();
                objListViewItem.SubItems.Add(String.Format("{0:dd/MM/yyyy}", lstItem[i].NgayKham.Value));
                lstvData.Items.Add(objListViewItem);
            }
        }

        /// <summary>
        /// Init hidden fields
        /// </summary>
        public void InitHiddenFields()
        {
            // Add a new textbox
            txtMaBenhNhan = new DevComponents.DotNetBar.Controls.TextBoxX
            {
                Name = "txtMaBenhNhan",
                Text = ""
            };
            txtMaBenhNhan.Visible = false;
        }

        /// <summary>
        ///  function is used to transfer data when event would be raised
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void TransferDataInfo(object sender, TransferSimpleDataEvent e)
        {
            this.Handler(this, e);
        }

        /// <summary>
        /// Validate user inputs
        /// </summary>
        /// <returns></returns>
        public bool ValidateUserInput(ref string errorText)
        {
            if (txtMaPhieu.Text == "")
            {
                errorText = "Vui lòng nhập phiếu khám";
                return false;
            }
            return true;
        }

        /// <summary>
        /// Add a new item to DB
        /// </summary>
        /// <returns></returns>
        private bool ActionAdd()
        {
            try
            {
                // Open connection
                DataContext.Instance.Connection.Open();
                // Define a transaction for the operations
                using (var transaction = DataContext.Instance.Connection.BeginTransaction())
                {
                    var newItem = new PhieuKham
                    {
                        MaPK = txtMaPhieu.Text,
                        MaBN = txtMaBenhNhan.Text,
                        MaBSLapPhieu = GlobalVars.g_CurrentUser.MaNguoiDung,
                        NgayKham = DateTime.Now,
                        KetLuanChung = txtKetLuanChung.Text,
                        GhiChu = txtGhiChu.Text,
                        NgayTaiKham = dtNgayTaiKham.Value
                    };

                    if (!PhieuKhamRepository.Insert(newItem))
                    {
                        return false;
                    }

                    // Insert phieu kham dich vu
                    for (int i = 0; i < lstvDanhSachDV.Items.Count; i++)
                    {
                        var phieukham_dv = new PhieuKham_DichVu
                        {
                            MaPK = newItem.MaPK,
                            MaDV = lstvDanhSachDV.Items[i].SubItems[4].Text,
                            MaBSNV = lstvDanhSachDV.Items[i].SubItems[5].Text,
                            KetLuanDV = lstvDanhSachDV.Items[i].SubItems[2].Text,
                            GhiChu = lstvDanhSachDV.Items[i].SubItems[3].Text
                        };
                        if (!PhieuKham_DichVuRepository.Insert(phieukham_dv))
                        {
                            return false;
                        }
                    }

                    // Insert phieu kham thuoc
                    for (int i = 0; i < lstvDanhSachThuoc.Items.Count; i++)
                    {
                        var phieukham_thuoc = new PhieuKham_Thuoc
                        {
                            MaPK = newItem.MaPK,
                            MaThuoc = lstvDanhSachThuoc.Items[i].SubItems[4].Text,
                            SoLuong = int.Parse(lstvDanhSachThuoc.Items[i].SubItems[2].Text)
                        };
                        if (!PhieuKham_ThuocRepository.Insert(phieukham_thuoc))
                        {
                            return false;
                        }
                    }

                    // Mark the transaction as complete
                    transaction.Commit();
                    DataContext.Instance.Connection.Close();
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// Update an item in DB
        /// </summary>
        /// <returns></returns>
        private bool ActionUpdate()
        {
            try
            {
                // Open connection
                DataContext.Instance.Connection.Open();
                // Define a transaction for the operations
                using (var transaction = DataContext.Instance.Connection.BeginTransaction())
                {
                    var updateItem = PhieuKhamRepository.SelectByID(txtMaPhieu.Text);
                    updateItem.KetLuanChung = txtKetLuanChung.Text;
                    updateItem.GhiChu = txtGhiChu.Text;
                    updateItem.NgayTaiKham = dtNgayTaiKham.Value;

                    if (!PhieuKhamRepository.Save())
                    {
                        return false;
                    }


                    // Removew old phieukham_dv
                    var lstItem = PhieuKham_DichVuRepository.SelectByMaPK(updateItem.MaPK);
                    foreach (var item in lstItem)
                    {
                        var lstChiSo = ChiSo_PhieuKhamDVRepository.SelectByMaPKDV(item.MaPKDV);
                        for (int i = 0; i < lstChiSo.Count; i++)
                        {
                            if (!ChiSo_PhieuKhamDVRepository.Delete(lstChiSo[i].MaCSPKDV))
                            {
                                return false;
                            }
                        }
                        if (!PhieuKham_DichVuRepository.Delete(item.MaPKDV))
                        {
                            return false;
                        }
                    }

                    // add new phieukham_dv
                    for (int i = 0; i < lstvDanhSachDV.Items.Count; i++)
                    {
                        var phieukham_dv = new PhieuKham_DichVu
                        {
                            MaPK = updateItem.MaPK,
                            MaDV = lstvDanhSachDV.Items[i].SubItems[4].Text,
                            MaBSNV = lstvDanhSachDV.Items[i].SubItems[5].Text,
                            KetLuanDV = lstvDanhSachDV.Items[i].SubItems[2].Text,
                            GhiChu = lstvDanhSachDV.Items[i].SubItems[3].Text
                        };
                        if (!PhieuKham_DichVuRepository.Insert(phieukham_dv))
                        {
                            return false;
                        }
                    }

                    // Removew old phieukham_thuoc
                    var lstItem2 = PhieuKham_ThuocRepository.SelectByMaPK(updateItem.MaPK);
                    foreach (var item in lstItem2)
                    {
                        if (!PhieuKham_ThuocRepository.Delete(item.MaPKThuoc))
                        {
                            return false;
                        }
                    }

                    // add new phieukham_dv
                    for (int i = 0; i < lstvDanhSachThuoc.Items.Count; i++)
                    {
                        var phieukham_thuoc = new PhieuKham_Thuoc
                        {
                            MaPK = updateItem.MaPK,
                            MaThuoc = lstvDanhSachThuoc.Items[i].SubItems[4].Text,
                            SoLuong = int.Parse(lstvDanhSachThuoc.Items[i].SubItems[2].Text)
                        };
                        if (!PhieuKham_ThuocRepository.Insert(phieukham_thuoc))
                        {
                            return false;
                        }
                    }

                    // Mark the transaction as complete
                    transaction.Commit();
                    DataContext.Instance.Connection.Close();
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// Load info of current quatrinh
        /// If mode is insert: update txtMaKhenThuong
        /// Else: not change
        /// </summary>
        public void LoadCurrentQuaTrinhInfo(string id)
        {
            var lstItem = PhieuKham_DichVuRepository.SelectByMaPK(id);
            lstvDanhSachDV.Items.Clear();
            for(int i=0; i<lstItem.Count; i++)
            {
                var objListViewItem = new ListViewItem();
                objListViewItem.Tag = lstItem[i];
                objListViewItem.Text = lstItem[i].DichVu.TenDV;
                objListViewItem.SubItems.Add(lstItem[i].BacSi_NhanVien.ToString());
                objListViewItem.SubItems.Add(lstItem[i].KetLuanDV);
                objListViewItem.SubItems.Add(lstItem[i].GhiChu);
                objListViewItem.SubItems.Add(lstItem[i].MaDV);
                objListViewItem.SubItems.Add(lstItem[i].MaBSNV);
                lstvDanhSachDV.Items.Add(objListViewItem);
            }

            var lstItem2 = PhieuKham_ThuocRepository.SelectByMaPK(id);
            lstvDanhSachThuoc.Items.Clear();
            for (int i = 0; i < lstItem2.Count; i++)
            {
                var objListViewItem = new ListViewItem();
                objListViewItem.Tag = lstItem2[i];
                objListViewItem.Text = lstItem2[i].Thuoc.TenThuoc;
                objListViewItem.SubItems.Add(lstItem2[i].Thuoc.DonViTinh.TenDV);
                objListViewItem.SubItems.Add(lstItem2[i].SoLuong.ToString());
                objListViewItem.SubItems.Add(String.Format("{0:#,##0;Nothing}", lstItem2[i].Thuoc.Gia));
                objListViewItem.SubItems.Add(lstItem2[i].MaThuoc);
                lstvDanhSachThuoc.Items.Add(objListViewItem);
            }

            var phieu = PhieuKhamRepository.SelectByID(id);
            if (phieu != null)
            {
                txtKetLuanChung.Text = phieu.KetLuanChung == null ? "" : phieu.KetLuanChung;
                txtGhiChu.Text = phieu.GhiChu == null ? "" : phieu.GhiChu;
                dtNgayTaiKham.Value = phieu.NgayTaiKham == null ? DateTime.MinValue : (phieu.NgayTaiKham == DateTime.MinValue ? DateTime.MinValue : phieu.NgayTaiKham.Value);
                txtNgayKham.Text = String.Format("{0:dd/MM/yyyy}", phieu.NgayKham.Value);
            }
        }

        /// <summary>
        /// Disable them, xoa, sua
        /// </summary>
        public void DisableCmdButtons()
        {
            btnThem.Enabled = false;
            btnSua.Enabled = false;
            btnXoa.Enabled = false;
        }

        /// <summary>
        /// Erase data in textboxes when mode is insert
        /// </summary>
        public void EraseTextboxes()
        {
            lstvDanhSachDV.Items.Clear();
            lstvDanhSachThuoc.Items.Clear();
            txtKetLuanChung.Text = "";
            txtGhiChu.Text = "";
            dtNgayTaiKham.Value = DateTime.MinValue;
        }

        /// <summary>
        /// Set default status
        /// </summary>
        /// <param name="val">default is true</param>
        public void SetDefaultMode(bool val = true)
        {
            txtMaPhieu.ReadOnly = val;
            txtKetLuanChung.ReadOnly = val;
            txtGhiChu.ReadOnly = val;

            btnThemVaoDanhSachDV.Enabled = !val;
            btnXoaKhoiDanhSachDV.Enabled = !val;
            btnCapNhatKetLuanDichVu.Enabled = !val;

            btnThemVaoDSThuoc.Enabled = !val;
            btnXoaKhoiDanhSachThuoc.Enabled = !val;

            btnThem.Enabled = val;
            btnSua.Enabled = val;
            btnXoa.Enabled = val;
            btnGhi.Enabled = !val;
            btnHuy.Enabled = !val;
        }

        private void txtNam_KeyPress(object sender, KeyPressEventArgs e)
        {
            // Only allow type number
            if (!char.IsNumber(e.KeyChar) && (Keys)e.KeyChar != Keys.Back)
            {
                e.Handled = true;
            }
        }

        private void FrmNhapQuaTrinhKhenThuong_Shown(object sender, EventArgs e)
        {
        }

        private void btnThemVaoDanhSach_Click(object sender, EventArgs e)
        {
            FrmCapNhatDVSuDung frm = new FrmCapNhatDVSuDung();
            frm.Handler += ThemVaoDanhSachDV;
            frm.ShowDialog();
        }

        public void ThemVaoDanhSachDV(object sender, EventArgs e)
        {
            var eventType = (TransferSimpleDataEvent)e;
            string[] comp = eventType.Data.Split(new char[] { '#' });

            var dichvu = DichVuRepository.SelectByID(comp[0]);
            var bacsi = BacSi_NhanVienRepository.SelectByID(comp[1]);
            
            var objListViewItem = new ListViewItem();
            objListViewItem.Text = dichvu.TenDV;
            objListViewItem.SubItems.Add(bacsi.ToString());
            objListViewItem.SubItems.Add("");
            objListViewItem.SubItems.Add("");
            // Add madv and mabs
            objListViewItem.SubItems.Add(comp[0]);
            objListViewItem.SubItems.Add(comp[1]);
            lstvDanhSachDV.Items.Add(objListViewItem);
        }

        private void btnXoaKhoiDanhSach_Click(object sender, EventArgs e)
        {
            if (lstvDanhSachDV.SelectedItems.Count > 0)
            {
                lstvDanhSachDV.Items.RemoveAt(lstvDanhSachDV.SelectedIndices[0]);
            }
        }

        private void btnThemVaoDSThuoc_Click(object sender, EventArgs e)
        {
            FrmCapNhatToaThuoc frm = new FrmCapNhatToaThuoc();
            frm.Handler += ThemVaoToaThuoc;
            frm.ShowDialog();
        }

        public void ThemVaoToaThuoc(object sender, EventArgs e)
        {
            var eventType = (TransferSimpleDataEvent)e;
            string[] comp = eventType.Data.Split(new char[] { '#' });

            var thuoc = ThuocRepository.SelectByID(comp[0]);

            var objListViewItem = new ListViewItem();
            objListViewItem.Text = thuoc.TenThuoc;
            objListViewItem.SubItems.Add(thuoc.DonViTinh.TenDV);
            objListViewItem.SubItems.Add(comp[1]);
            objListViewItem.SubItems.Add(String.Format("{0:#,##0;Nothing}", thuoc.Gia));
            // Add mathuoc
            objListViewItem.SubItems.Add(comp[0]);
            lstvDanhSachThuoc.Items.Add(objListViewItem);
        }

        private void btnXoaKhoiDanhSachThuoc_Click(object sender, EventArgs e)
        {
            if (lstvDanhSachThuoc.SelectedItems.Count > 0)
            {
                lstvDanhSachThuoc.Items.RemoveAt(lstvDanhSachThuoc.SelectedIndices[0]);
            }
        }

        private void lstvDanhSachDV_DoubleClick(object sender, EventArgs e)
        {
            if (lstvDanhSachDV.SelectedItems.Count > 0 && btnCapNhatKetLuanDichVu.Enabled)
            {
                var dichvu = lstvDanhSachDV.SelectedItems[0].SubItems[4].Text;
                var bacsi = lstvDanhSachDV.SelectedItems[0].SubItems[5].Text;
                FrmCapNhatDVSuDung frm = new FrmCapNhatDVSuDung(dichvu, bacsi, ((PhieuKham_DichVu)lstvDanhSachDV.SelectedItems[0].Tag).MaPKDV);
                frm.Handler += CapNhatDichVuSuDung;
                frm.ShowDialog();
            }
        }

        private void btnCapNhatKetLuanDichVu_Click(object sender, EventArgs e)
        {
            if (lstvDanhSachDV.SelectedItems.Count > 0)
            {
                var dichvu = lstvDanhSachDV.SelectedItems[0].SubItems[4].Text;
                var bacsi = lstvDanhSachDV.SelectedItems[0].SubItems[5].Text;
                FrmCapNhatDVSuDung frm = new FrmCapNhatDVSuDung(dichvu, bacsi, ((PhieuKham_DichVu)lstvDanhSachDV.SelectedItems[0].Tag).MaPKDV);
                frm.Handler += CapNhatDichVuSuDung;
                frm.ShowDialog();
            }
        }

        public void CapNhatDichVuSuDung(object sender, EventArgs e)
        {
            var eventType = (TransferSimpleDataEvent)e;
            string[] comp = eventType.Data.Split(new char[] { '#' });

            lstvDanhSachDV.SelectedItems[0].SubItems[2].Text = comp[0];
            lstvDanhSachDV.SelectedItems[0].SubItems[3].Text = comp[1];
        }

        private void btnInPhieuKham_Click(object sender, EventArgs e)
        {
            if (txtMaPhieu.Text != "")
            {
                FrmInPhieu frm = new FrmInPhieu(PhieuKham_DichVuRepository.SelectByMaPK(txtMaPhieu.Text), PhieuKhamRepository.SelectByID(txtMaPhieu.Text));
                frm.ShowDialog();
            }
        }

        private void btnInHoaDon_Click(object sender, EventArgs e)
        {
            if (txtMaPhieu.Text != "")
            {
                FrmInHoaDonThanhToan frm = new FrmInHoaDonThanhToan(PhieuKham_DichVuRepository.SelectByMaPK(txtMaPhieu.Text), PhieuKhamRepository.SelectByID(txtMaPhieu.Text));
                frm.ShowDialog();
            }
        }

        private void btnInToaThuoc_Click(object sender, EventArgs e)
        {
            if (txtMaPhieu.Text != "")
            {
                FrmInToaThuoc frm = new FrmInToaThuoc(PhieuKham_ThuocRepository.SelectByMaPK(txtMaPhieu.Text), PhieuKhamRepository.SelectByID(txtMaPhieu.Text));
                frm.ShowDialog();
            }
        }
    }
}